package com.dco.signature.service;

import com.dco.signature.model.Signature;
import com.dco.signature.repository.SignatureRepository;
import com.dco.signature.exception.AlreadySignedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DcoService {

    @Autowired
    private SignatureRepository signatureRepository;

    // 签署DCO
    public Signature signDco(String repoUrl, String name, String email) {
        // 检查是否已经签署
        boolean exists = signatureRepository.existsByRepoUrlAndNameAndEmail(repoUrl, name, email);
        if (exists) {
            throw new AlreadySignedException("您已经签署过该仓库的DCO，无法重复签署。");
        }

        // 创建签名信息
        Signature signature = new Signature(repoUrl, name, email, LocalDateTime.now());
        // 保存到数据库
        return signatureRepository.save(signature);
    }

    // 查询签署状态
    public boolean hasSigned(String repoUrl, String email) {
        return signatureRepository.existsByRepoUrlAndEmail(repoUrl, email);
    }

    // 获取所有签署者
    public List<Signature> getSignatures(String repoUrl) {
        return signatureRepository.findByRepoUrl(repoUrl);
    }
}
